#include "uart_bus.h"


struct tagUartBus *UarBus[] = {
		stm32f4xx_uart,
		stm32f4xx_uart + 1,
		stm32f4xx_uart + 2,
		stm32f4xx_uart + 3		
};

const uint32_t get_uartbus_nl = sizeof(UarBus)/sizeof(struct tagUartBus *);

_declare_box(uart_mpool,nlUARTBUFF,nlUARTBUS);

void UartBus_Init(void)
{
		uint32_t i;				
		for (i = 0; i < get_uartbus_nl; i++) { 
				if (UarBus[i])
				if (UarBus[i]->operate)
				if (UarBus[i]->operate->initialize) {
						UarBus[i]->operate->initialize(UarBus[i]);						
						UarBus[i]->agreement = NULL;
						os_sem_init (UarBus[i]->semaphore, 1);	
				}		
		}
		_init_box (uart_mpool, sizeof (uart_mpool), nlUARTBUFF);
}

int32_t UartBus_LinkAgreement(struct tagUartBus *pUb,struct tagUartAgreement *pUagr,const uint16_t timeout)
{		
    
		if (os_sem_wait (pUb->semaphore, timeout) == OS_R_TMO) return -1;
		
		pUb->agreement = pUagr;
		pUagr->uartbus = pUb;

		pUagr->box = _calloc_box (uart_mpool);
		if (pUagr->box == NULL) {
				pUb->agreement = NULL;
				pUagr->uartbus = NULL;
				os_sem_send (pUb->semaphore);
				return -1;
		}
		
		return 0;				
}

void UartBus_UnLinkAgreement(struct tagUartBus *pUb,struct tagUartAgreement *pUagr)
{
		if (pUagr->box) {
				_free_box (uart_mpool, pUagr->box);
		}
			
		pUb->agreement = NULL;
		pUagr->uartbus = NULL;

		os_sem_send (pUb->semaphore);				
}
